package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.annotations.Until;
import com.itheima.advice.LogOperation;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Autowired
    private EmpService empService;

    @Autowired
    private DeptService deptService;
    @GetMapping
    public Result findPage(EmpQueryParam param)
    {
        Page<Emp> page = new Page<>(param.getPage(),param.getPageSize());
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(param.getName()),Emp::getName,param.getName());
        wrapper.eq(param.getGender()!=null,Emp::getGender,param.getGender());
        wrapper.between(param.getBegin()!=null&&param.getEnd()!=null,Emp::getEntryDate,param.getBegin(),param.getEnd());
         page = empService.page(page, wrapper);

        List<Emp> empList = page.getRecords();
        empList.forEach((emp)->{
            if(emp.getDeptId()!=null) {
                Dept dept = deptService.getById(emp.getDeptId());
                if (dept != null) {
                    emp.setDeptName(dept.getName());
                }
            }

        });


        PageResult<Emp> pageResult = new PageResult<>(page.getTotal(),page.getRecords());
        return Result.success(pageResult);

    }
    @PostMapping
    @LogOperation
    public Result save(@RequestBody Emp emp)
    {

        empService.saveEmpAndExpr(emp);
        return Result.success();

    }
    @DeleteMapping
    @LogOperation
    Result delete(@RequestParam List<Integer> ids){

        empService.deleteEmpAndExpr(ids);
        return Result.success();
    }

    @GetMapping("/{id}")
    Result getById(@PathVariable Integer id){
        Emp emp = empService.getEmpAndExprById(id);
        return Result.success(emp);
    }

    @PutMapping
    @LogOperation
    Result updateById(@RequestBody Emp emp){
        empService.updateEmpAndExprById(emp);
        return Result.success();
    }
    @GetMapping("/list")
    Result findAll(){
        List<Emp> empList = empService.list();
        return Result.success(empList);
    }


}
